package com.cf.zookeeper.service;

import com.cf.constant.EnumReturnCode;
import com.cf.exception.BizException;
import com.cf.zookeeper.model.Zookeeper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ZkCache {

    @Autowired
    private ZookeeperService zookeeperService;

    private static Map<Long, ZkManager> cache = new ConcurrentHashMap<Long, ZkManager>();

    public synchronized ZkManager get(long key) {
        ZkManager zkManager = cache.get(key);
        if (zkManager == null) {
            Zookeeper zookeeper = zookeeperService.selectOne(key);
            if (zookeeper == null) {
                throw new BizException(EnumReturnCode.ERROR.getCode(), "zookeeper数据不存在！");
            }
            ZkManagerImpl zk = new ZkManagerImpl();
            zkManager = zk.connect(zookeeper.getAddress(), zookeeper.getTimeout());
            cache.put(key, zk);
        }
        return zkManager;
    }


}
